package com.ruin.tech.ahri.service.impl;

import com.ruin.tech.ahri.dao.BookMapper;
import com.ruin.tech.ahri.model.dto.Book;
import com.ruin.tech.ahri.model.dto.BookDTO;
import com.ruin.tech.ahri.model.dto.BookExample;
import com.ruin.tech.ahri.service.IBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @program ahri
 * @description: 预约服务
 * @author: ruin
 * @create: 2019/12/26 09:38
 */

@Slf4j
@Service
public class BookServiceImpl implements IBookService {

    @Autowired
    BookMapper bookMapper;

    @Override
    public void add(Book book) throws Exception {
        book.setCreateTime(new Date());
        book.setUpdateTime(new Date());
        book.setStatus(0);
        if(book.getUserId() == null){
            book.setUserId(0L);
        }
        bookMapper.insert(book);
    }

    @Override
    public List<Book> findPage(BookDTO bookDTO) throws Exception {
        BookExample bookExample = new BookExample();
        BookExample.Criteria cri = bookExample.createCriteria();
        cri.andStatusEqualTo(bookDTO.getStatus());
        if(bookDTO.getRoleType()!=null && bookDTO.getRoleType().equals(99)){
            cri.andUserIdEqualTo(bookDTO.getUserId());
        }

        if(bookDTO.getPageNum() != null && bookDTO.getPageSize() != null) {
            bookExample.setOrderByClause(" book_date_time desc limit " + (bookDTO.getPageNum() - 1) * bookDTO.getPageSize() + "," + bookDTO.getPageSize());
        }else{
            bookExample.setOrderByClause(" book_date_time desc");
        }
        return bookMapper.selectByExample(bookExample);
    }

    @Override
    public void del(BookDTO bookDTO) throws Exception {
        BookExample bookExample = new BookExample();
        bookExample.createCriteria().andIdEqualTo(bookDTO.getId());
        bookMapper.deleteByExample(bookExample);
    }

    @Override
    public void edit(Book book) throws Exception {
        BookExample bookExample = new BookExample();
        book.setUpdateTime(new Date());
        bookExample.createCriteria().andIdEqualTo(book.getId());
        bookMapper.updateByExampleSelective(book,bookExample);
    }
}
